package cn.itcast.music.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import cn.itcast.music.R;
import cn.itcast.music.entity.Music;
import cn.itcast.music.ui.home.MusicListAdapter.ViewHolder;
import cn.itcast.music.ui.listen.ListenActivity;
import cn.itcast.music.util.DateTimeUtil;
import cn.itcast.music.util.MusicUtil;
import java.util.List;

public class MusicListAdapter extends RecyclerView.Adapter<ViewHolder> {

    private final List<Music> musicList;

    public MusicListAdapter(List<Music> musicList) {
        this.musicList = musicList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,
            int viewType) {
        View view = View.inflate(parent.getContext(), R.layout.item_song, null);
        return new ViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Music music = musicList.get(position);
        holder.ivSong.setImageBitmap(
                MusicUtil.getAlbumBitmap(holder.itemView.getContext(),
                        music.getPath()));
        holder.tvTitle.setText(music.getTitle());
        holder.tvArtist.setText(music.getArtist() + " - " + music.getAlbum());
        holder.tvDuration.setText(
                DateTimeUtil.formatTime(music.getDuration()));
        holder.itemView.setOnClickListener(view -> {
            Log.d("App-MusicListAdapter", "用户点击音乐！" + music);
            // 跳转到播放界面
            Intent intent = new Intent(view.getContext(), ListenActivity.class);
            // 这里的 position 就是音乐列表的 position，无需浪费性能开销去查询
            intent.putExtra("position", position);
            view.getContext().startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return musicList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView ivSong;

        TextView tvTitle;

        TextView tvArtist;

        TextView tvDuration;


        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivSong = itemView.findViewById(R.id.iv_song);
            tvTitle = itemView.findViewById(R.id.tv_title);
            tvArtist = itemView.findViewById(R.id.tv_artist);
            tvDuration = itemView.findViewById(R.id.tv_duration);
        }

    }

}
